import dayjs from "dayjs";
import { ref, onMounted, Ref } from "vue";
import {
  getDbList,
  setDbBackup,
  setDbOptimize,
  setDbRepair,
  getFileList,
  fileDel,
  fileDownload,
  fileImport
} from "@/api/devtools/database";
import { getKeyList, extractFields, downloadByData } from "@pureadmin/utils";
import { message } from "@/utils/message";

export function useUser(tableRef: Ref) {
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const tableInfo = ref([]);
  const infoDrawer = ref(false);
  const infoTitle = ref();
  const fileList = ref([]);
  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left"
    },
    {
      label: "表名",
      prop: "name",
      width: 120,
      align: "left"
    },
    {
      label: "存储引擎",
      prop: "engine",
      width: 90
    },
    {
      label: "行格式",
      prop: "row_format",
      width: 90
    },
    {
      label: "数据长度",
      prop: "data_length",
      width: 90
    },
    {
      label: "索引长度",
      prop: "index_length",
      width: 90
    },
    {
      label: "未用空间量",
      prop: "data_free",
      width: 100
    },
    {
      label: "行数",
      prop: "rows",
      width: 80
    },
    {
      label: "自增值",
      prop: "auto_increment",
      width: 80
    },
    {
      label: "字符集",
      prop: "collation",
      width: 180
    },
    {
      label: "注释",
      prop: "comment",
      width: 200
    },
    {
      label: "创建时间",
      width: 200,
      prop: "create_time"
    },
    {
      label: "更新时间",
      width: 200,
      prop: "update_time"
    },
    {
      label: "操作",
      fixed: "right",
      minWidth: 50,
      slot: "operation"
    }
  ];

  const infoColumns: TableColumnList = [
    {
      label: "字段名",
      prop: "field",
      width: 120,
      align: "left"
    },
    {
      label: "类型",
      prop: "type",
      width: 90
    },
    {
      label: "默认值",
      prop: "default",
      width: 90
    },
    {
      label: "可否为空",
      prop: "null",
      width: 90
    },
    {
      label: "字符集",
      prop: "collation",
      width: 130
    },

    {
      label: "额外信息",
      prop: "extra",
      width: 130
    },
    {
      label: "索引信息",
      prop: "key",
      width: 90
    },
    {
      label: "注释",
      prop: "comment",
      minWidth: 120
    }
  ];

  const fileColumns: TableColumnList = [
    {
      label: "名称",
      prop: "name",
      fixed: "left",
      align: "left",
      width: 200
    },
    {
      label: "大小",
      prop: "size",
      minWidth: 90
    },
    {
      label: "compress",
      prop: "compress",
      minWidth: 90
    },
    {
      label: "part",
      prop: "part",
      minWidth: 90
    },
    {
      label: "备份时间",
      prop: "time",
      minWidth: 90,
      formatter: ({ time }) =>
        time ? dayjs(dayjs.unix(time)).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "操作",
      fixed: "right",
      minWidth: 50,
      slot: "operation"
    }
  ];

  async function dbList() {
    const { data } = await getDbList();
    dataList.value = data.list;
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  //多选操作----备份、优化、修复
  function operation(func, name) {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const tableList = ref([]);
    tableList.value = getKeyList(curSelected, "name");
    const nameStr = tableList.value.join(",");
    console.log(nameStr);
    if (func === setDbRepair) {
      tableList.value = extractFields<any, string>(
        curSelected,
        "name",
        "engine"
      );
    }

    func({ tables: tableList.value }).then(res => {
      if (res.code == 200) {
        message(`选中的表 ${nameStr} ${name}成功！`, { type: "success" });
      } else {
        message(`选中的表 ${nameStr} ${name}失败！失败原因： ${res.error}`, {
          type: "error",
          showClose: true,
          customClass: "el"
        });
      }
    });
    tableRef.value.getTableRef().clearSelection();
  }

  //获取表详情
  function getTableInfo(row) {
    infoDrawer.value = true;
    infoTitle.value =
      row.name + (row.comment ? "（" + row.comment + "）" : "") + "详细信息";
    getDbList({ table: row.name }).then(res => {
      if (res.code == 200) {
        tableInfo.value = res.data.list;
      } else {
        message(res.error, { type: "error" });
      }
    });
  }

  //备份列表
  async function backupList() {
    const { data } = await getFileList();
    fileList.value = data.list;
  }

  //删除备份
  function handleFileDel(row) {
    fileDel({ time: row.time }).then(async res => {
      if (res.code == 200) {
        message("删除成功!", { type: "success" });
        backupList();
      } else {
        message("删除失败! 原因：" + res.error, { type: "success" });
      }
    });
  }

  //下载备份文件
  function handleFileDownload(row) {
    fileDownload({ time: row.time }).then(({ data, headers }: any) => {
      const filenameRegex = /filename=([^;]*)/;
      const matches = filenameRegex.exec(headers.get("content-disposition"));
      downloadByData(data, decodeURI(matches[1]));
    });
  }

  //导入备份文件
  function handleFileImport(row) {
    fileImport({ time: row.time, part: row.part }).then(res => {
      if (res.code == 200) {
        message("导入成功！", { type: "success" });
      } else {
        message(res.error, { type: "error" });
      }
    });
  }

  onMounted(async () => {
    dbList();
    backupList();
    loading.value = false;
  });

  return {
    loading,
    columns,
    dataList,
    operation,
    selectedNum,
    onSelectionCancel,
    handleSelectionChange,
    setDbBackup,
    setDbOptimize,
    setDbRepair,
    getTableInfo,
    tableInfo,
    infoDrawer,
    infoColumns,
    infoTitle,
    fileColumns,
    fileList,
    handleFileDel,
    handleFileDownload,
    backupList,
    dbList,
    handleFileImport
  };
}
